<template>
  <div class="xjjl-add">
    <van-cell :title="fyInfo.roomName" value="" :label="fyInfo.placeInfo.placeName" />
    <van-form @submit="onSubmit" class="margin-top-12" :show-error-message="false">
      <p class="header-title">房间问题</p>
      <van-field
        v-model="formParams.roomProblem"
        rows="3"
        autosize
        label="存在的问题"
        type="textarea"
        placeholder="请输入存在的问题"
        name="roomProblem"
        :rules="[{ required: true, message: '请输入存在的问题' }]"
        required
      />
      <van-field name="uploader" label="图片">
        <template #input>
          <van-uploader v-model="fileList" :deletable="true" :after-read="afterRead" @delete="deleteFile"/>
        </template>
      </van-field>

      <p class="header-title">场所问题</p>
      <p class="descript-title" style="padding-bottom: 6px;">加扣分明细</p>
      <van-cell-group>
        <van-cell class="show-cell-item" :title="item.scoreItem" :value="item.scoreType == '加分' ? '+' + item.score :  '-' + item.score" v-for="(item, index) in dealjkfmxList" :key="index" />
      </van-cell-group>
      <div class="add-button">
        <van-button icon="plus" plain hairline type="info" @click.prevent="goDetail('/xjjl-jkfmx')" block>新增加扣分明细</van-button>
      </div>

      <p class="descript-title margin-top-12">挂牌</p>
      <van-field
        clickable
        readonly
        name="cardType"
        :value="formParams.cardType"
        label="挂牌类型"
        placeholder="点击选择挂牌类型"
        :rules="[{ required: false, message: '请选择挂牌类型' }]"
        @click="showPickergplx = true"
      />
      <van-field
        clickable
        readonly
        name="cardItem"
        :value="formParams.cardItem"
        label="挂牌细则"
        placeholder="点击选择挂牌细则"
        :rules="[{ required: (formParams.cardType ? true : false), message: '请选择挂牌细则' }]"
        :required="formParams.cardType ? true : false"
        @click="showPickergpxz = true"
      />
      <van-field
        v-model="formParams.cardBz"
        rows="3"
        autosize
        label="挂牌说明"
        type="textarea"
        placeholder="请输入挂牌说明"
        name="cardBz"
        :rules="[{ required: false, message: '请输入挂牌说明' }]"
      />
      <van-field
        clickable
        readonly
        name="rectStartTime"
        :value="formParams.rectStartTime"
        label="整改开始时间"
        placeholder="点击选择整改开始时间"
        :rules="[{ required: (formParams.cardType ? true : false), message: '请选择整改开始时间' }]"
        :required="formParams.cardType ? true : false"
        :min-date="minDate"
        @click="showPickerzgkssj = true"
      />
      <van-field
        clickable
        readonly
        name="rectEndTime"
        :value="formParams.rectEndTime"
        label="整改结束时间"
        placeholder="点击选择整改结束时间"
        :min-date="minDate"
        :rules="[{ required: (formParams.cardType ? true : false), message: '请选择整改结束时间' }]"
        :required="formParams.cardType ? true : false"
        @click="showPickerzgjssj = true"
      />

      <p class="descript-title" style="padding-bottom: 6px; margin-top: 12px;">事件反馈</p>
      <van-cell-group>
        <van-cell class="show-cell-item" :title="item.eventContent" value="" v-for="(item, index) in dealsjfkList" :key="index" />
      </van-cell-group>
      <div class="add-button">
        <van-button icon="plus" plain hairline type="info" @click.prevent="goDetail('/xjjl-sjfk')" block>新增事件反馈</van-button>
      </div>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>

    </van-form>
    <!-- pop自定义 -->
    <van-popup v-model="showPickergpxz" position="bottom">
      <van-picker
        title="挂牌细则"
        show-toolbar
        :columns="gpxzList"
        value-key="label"
        cancel-button-text="清空"
        @confirm="onConfirmGpxz"
        @cancel="() => (showPickergpxz = false, formParams.cardItem = '')"
        :default-index="0"
      />
    </van-popup>
    <van-popup v-model="showPickergplx" position="bottom">
      <van-picker
        title="挂牌类型"
        show-toolbar
        :columns="gplxList"
        cancel-button-text="清空"
        @confirm="onConfirmGplx"
        @cancel="() => (showPickergplx = false, formParams.cardType = '', formParams.cardItem = '', formParams.cardBz = '', formParams.rectStartTime = '', formParams.rectEndTime = '')"
        :default-index="0"
      />
    </van-popup>
    <van-calendar v-model="showPickerzgkssj" @confirm="onConfirmZgkssj" />
    <van-calendar v-model="showPickerzgjssj" @confirm="onConfirmZgjssj" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { addInspection } from '@/api/xjgl';
import { upload } from '@/api/common';
export default {
  name: 'xjjl-add',
  dicts: ['ptsj_red_card_item', 'ptsj_yellow_card_item', 'ptsj_blue_card_item'],
  data() {
    return {
      fyInfo: JSON.parse(window.localStorage.getItem('fyInfo')),
      formParams: {
        roomProblem: '',
        cardType: '',
        cardItem: '',
        cardBz: '',
        rectStartTime: '',
        rectEndTime: ''
      },
      fileList: [],
      fileListHt: [],
      fjBackList: [],
      gpxzList: [],
      gplxList: ['蓝牌', '黄牌', '红牌'],
      showPickerlx: false, // 加扣分类型
      showPickergplx: false, // 挂牌类型
      showPickergpxz: false, // 挂牌细则
      showPickerzgkssj: false,
      showPickerzgjssj: false, // 整改结束时间
      minDate: new Date(new Date().getFullYear(), (new Date().getMonth() + 1), new Date().getDay()),
    }
  },
  computed: {
    ...mapGetters(['jkfmxList', 'sjfkList']),
    dealjkfmxList() {
      let { jkfmxList } = this;
      if(window.localStorage.getItem('jkfmxList')) {
        return JSON.parse(window.localStorage.getItem('jkfmxList'));
      } else {
        return jkfmxList
      }
    },
    dealsjfkList() {
      let { sjfkList } = this;
      if(window.localStorage.getItem('sjfkList')) {
        return JSON.parse(window.localStorage.getItem('sjfkList'));
      } else {
        return sjfkList
      }
    }
  },
  mounted() {
    if(sessionStorage.getItem('nowPageData')) {
      this.formParams = JSON.parse(sessionStorage.getItem('nowPageData'))
    }
    if(sessionStorage.getItem('fileList')) {
      this.fileList = JSON.parse(sessionStorage.getItem('fileList'))
    }
    if(sessionStorage.getItem('fjBackList')) {
      this.fjBackList = JSON.parse(sessionStorage.getItem('fjBackList'))
    }
  },
  methods: {
    goDetail(path) {
      sessionStorage.setItem('nowPageData', JSON.stringify(this.formParams));
      sessionStorage.setItem('fileList', JSON.stringify(this.fileList));
      sessionStorage.setItem('fjBackList', JSON.stringify(this.fjBackList));
      this.$router.push(path)
    },
    async afterRead(fileObj) {
      console.log(fileObj);
      // 此时可以自行将文件上传至服务器
      let formData = new FormData();
      formData.append('file', fileObj.file);
      await upload(formData).then(res => {
        try {
          this.fileListHt.push(fileObj.file)
          // console.log(res)
          this.fjBackList.push({
            filename: res.fileName,
            newfilename: res.newFileName,
            originalfilename: res.originalFilename,
            url: res.url,
          })
        } catch(error) {
          console.log(error)
        }
      })
    },
    deleteFile(fileObj, detail) {
      // console.log(fileObj, detail)
      this.fjBackList.splice(detail.index, 1);
      // console.log(this.fjBackList)
    },
    async onSubmit(values) {
      await this.uploadImage();
      console.log('submit', values);
      if(values) {
        let params = values;
        params.placeCode = this.fyInfo.placeCode;
        params.roomId = this.fyInfo.houseCode;
        params.roomName = this.fyInfo.roomName;
        params.placeName = this.fyInfo.placeInfo.placeName;
        params.inspFiles = this.fjBackList;
        params.scoreList = this.dealjkfmxList;
        params.eventList = this.dealsjfkList;
        console.log(params)
        await addInspection(params).then(res => {
          console.log(res)
          if(res.code == 200) {
            window.localStorage.setItem('jkfmxList', '');
            window.localStorage.setItem('sjfkList', '');
            sessionStorage.clear()
            this.$router.go(-1)
          }
        })
      }
    },
    async uploadImage() {
      if(this.fileList.length > 0) {
        let formData = new FormData();
        for(let i= 0; i< this.fileListHt.length; i++) {
          formData.append('file', this.fileListHt[i]);
          await upload(formData).then(res => {
            try {
              // console.log(res)
              this.fjBackList.push({
                filename: res.fileName,
                newfilename: res.newFileName,
                originalfilename: res.originalFilename,
                url: res.url,
              })
            } catch(error) {
              console.log(error)
            }
          })
        }
      }
    },
    onConfirmGpxz(row, index) {
      this.formParams.cardItem = row.label;
      this.showPickergpxz = false;
    },
    onConfirmGplx(value, index) {
      if(value !== this.formParams.cardType) {
        this.formParams.cardItem = '';
      }
      this.formParams.cardType = value;
      this.showPickergplx = false;
      if(value == '红牌') {
        this.gpxzList = this.dict.type.ptsj_red_card_item
      } else if(value == '蓝牌') {
        this.gpxzList = this.dict.type.ptsj_blue_card_item
      } else if(value == '黄牌') {
        this.gpxzList = this.dict.type.ptsj_yellow_card_item
      } else {
        this.gpxzList = []
      }
    },
    onConfirmZgkssj(date) {
      this.showPickerzgkssj = false;
      this.formParams.rectStartTime = this.formatDate(date);
    },
    onConfirmZgjssj(date) {
      this.showPickerzgjssj = false;
      this.formParams.rectEndTime = this.formatDate(date);
    },
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth()}-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`;
    },
  }
}
</script>

<style lang="less" scoped>
.xjjl-add {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: #F5F5F5;
  /deep/ .van-cell__title {
    text-align: left;
  }
  /deep/ .van-field {
    display: block;
    .van-field__label {
      font-size: 13px;
      width: 90%;
    }
  }
  .margin-top-12 {
    margin-top: 12px;
  }
  .header-title {
    color: #666666;
    font-size: 12px;
    letter-spacing: 0px;
    text-align: left;
    padding: 12px 16px 4px;
  }
  .descript-title {
    background-color: #Fff;
    color: #666666;
    font-size: 12px;
    padding: 16px 16px 0px;
    text-align: left;
  }
  .show-cell-item {
    padding: 5px 16px;
  }
  .add-button {
    background-color: #Fff;
    padding: 12px 16px;
    box-sizing: border-box;
  }
}
</style>